/*
 * @Description: 
 * @Date: 2025-08-05 10:00:56
 * @LastEditTime: 2025-08-14 17:38:05
 */
import SockJS from 'sockjs-client/dist/sockjs.min.js';
import Stomp from 'stompjs';
import emitter from './eventBus'

// 发送事件

let stompClient = null;

export function connect(packageId) {
    
    const socket = new SockJS('http://8.152.202.68:10009/ws-quota'); // 连接后端 WebSocket 端点
    stompClient = Stomp.over(socket);

    stompClient.connect({}, function (frame) {
        console.log('Connected: ' + frame);
        stompClient.subscribe(`/topic/package-quota/${packageId}`, function (greeting) {
            const {available,max} = JSON.parse(greeting.body);
            emitter.emit('event-name', { available,max})
        });
    });
}

export function sendMessage(message) {
    if (stompClient) {
        stompClient.send("/app/hello", {}, JSON.stringify(message));
    }
}

export function disconnect() {
    if (stompClient) {
        stompClient.disconnect();
    }
    console.log("Disconnected");
}
